<script setup lang="ts">
import type {
  FormInstance,

  MessageBoxData,
} from 'element-plus'

import {
  calculationObj,
  defaultFormData,
  defaultVirtuallyFormData,
  virtuallyFormRules,
} from './index'
import type { CustomDialogInstance, IndicatorInfo, VirtuallyRelationSaveOrUpdate } from '@/types'

import {
  queryList,
  saveOrUpdate,
} from '@/api/modules/virtuallyRelation'
// ------------------use------------------
// #region
const props = defineProps<{
  title: string
  indicatorData: IndicatorInfo[]
}>()
const formData = defineModel('data', {
  default: () => defaultFormData,
})
const { $confirm } = useCurrentInstance()
const [virtuallyForm, setVirtuallyForm] = useState({
  ...defaultVirtuallyFormData,
})
const [tableData, setTableData] = useState<
  Partial<VirtuallyRelationSaveOrUpdate>[]
>([])
const [isEdit, setIsEdit] = useState(false)
// #endregion
// ------------------静态变量------------------
// #region

// #endregion
// ------------------动态变量------------------
// #region

// #endregion
// ------------------ref-----------
// #region
const dialogRef = ref<CustomDialogInstance | null>(null)
const formRef = ref<FormInstance | null>(null)
// #endregion
// ------------------reactive------
// #region
// #endregion
// ------------------computed------
// #region
const computedIndicatorData = computed(() => {
  const m = tableData.value.map(item => item.indicatorId)
  return props.indicatorData.filter(
    item => !m.includes(item.id ?? 0),
  )
  // return props.indicatorData.filter(
  //   item => !item.isVirtually && !m.includes(item.id ?? 0)
  // );
})
// #endregion
// ------------------生命周期------------------
// #region

// #endregion
// ------------------内置方法---------------------
// #region
// #endregion
// ------------------方法---------------------
// #region
async function getTableData() {
  console.log(formData.value.id)

  const { data: res } = await queryList(
    formData.value.id ?? 0,
  )
  removeUnnecessaryParams(res, ['id', 'indicatorCode'])
  console.log(res)

  setTableData(
    res as unknown as Partial<VirtuallyRelationSaveOrUpdate>[],
  )
}
async function open() {
  dialogRef.value?.open?.()
  await nextTick()
  dialogRef.value?.setSaving?.(false)
  formRef.value?.resetFields()
  await nextTick()
  getTableData()
}
function close() {
  dialogRef.value?.close?.()
}
async function clickSave() {
  await saveOrUpdate(tableData.value)
  close()
}
async function handleAddOrEdit() {
  const isValid = await formRef.value?.validateField()
  if (!isValid)
    return
  const params = {
    ...virtuallyForm.value,
    virtuallyIndicatorId: formData.value.id,
  }
  if (isEdit.value) {
    const m = tableData.value.find(
      item =>
        item.indicatorId === virtuallyForm.value.indicatorId,
    )
    m!.calculation = virtuallyForm.value.calculation
    // tableData.value
  }
  else {
    tableData.value.push(params)
  }
  await nextTick()
  setVirtuallyForm({ ...defaultVirtuallyFormData })
  setIsEdit(false)
}
function handleDelete() {
  const i = tableData.value.findIndex(
    item =>
      item.indicatorId === virtuallyForm.value.indicatorId,
  )
  tableData.value.splice(i, 1)
  handleClear()
}
async function handleBeforeClose(done: () => void) {
  const m: MessageBoxData = await $confirm(
    '数据可能未保存，确定关闭？',
    '警告',
    {
      type: 'warning',
    },
  ).catch(e => e)
  if (m !== 'confirm')
    return
  done()
}
function handleClear() {
  setVirtuallyForm({ ...defaultVirtuallyFormData })
  setIsEdit(false)
}
function handleClose() {
  handleBeforeClose(close)
}
function handleTableRowClick(row: VirtuallyRelationSaveOrUpdate) {
  setIsEdit(true)
  setVirtuallyForm({ ...defaultVirtuallyFormData, ...row })
}
// #endregion
defineExpose({
  open,
  close,
})
</script>

<template>
  <CustomDialog
    ref="dialogRef"
    :title="title"
    width="800px"
    :before-close="handleBeforeClose"
  >
    <div
      class="width-fill align-center dialog-container flex"
    >
      <div class="flex-sub height-fill">
        <el-table
          :data="tableData"
          class="width-fill height-fill"
          @row-click="handleTableRowClick"
        >
          <el-table-column label="指标">
            <template #default="{ row }">
              {{
                indicatorData.find(
                  item => item.id === row.indicatorId,
                )?.indicatorName
              }}
            </template>
          </el-table-column>
          <el-table-column label="关系">
            <template #default="{ row }">
              <span
                :class="[
                  calculationObj[row.calculation].class,
                ]"
              >
                {{ calculationObj[row.calculation].label }}
              </span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-divider
        direction="vertical"
        class="height-fill"
      />
      <div class="flex-sub height-fill">
        <el-form
          ref="formRef"
          label-width="50px"
          label-position="right"
          :model="virtuallyForm"
          :rules="virtuallyFormRules"
          inline
          class="width-fill"
        >
          <el-form-item
            label="指标"
            prop="indicatorId"
            class="width-fill"
          >
            <el-select
              v-model="virtuallyForm.indicatorId"
              filterable
              :disabled="isEdit"
              class="width-fill"
            >
              <el-option
                v-for="item in computedIndicatorData"
                :key="item.id"
                :label="item.indicatorName"
                :value="item.id!"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="关系"
            prop="calculation"
            class="width-fill"
          >
            <el-select
              v-model="virtuallyForm.calculation"
              class="width-fill"
            >
              <el-option
                v-for="(value, key) in calculationObj"
                :key="key"
                :label="`${value.value}  ${value.label}`"
                :value="+key"
                :class="value.class"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <div class="width-fill flex justify-center">
          <el-button

            text bg
            type="primary"
            @click="handleAddOrEdit"
          >
            {{ isEdit ? '编辑' : '新增' }}
          </el-button>
          <el-button
            v-show="isEdit"
            bg
            text
            type="danger"
            @click="handleDelete"
          >
            删除
          </el-button>
          <el-button bg text @click="handleClear">
            取消
          </el-button>
        </div>
      </div>
    </div>
    <div
      v-show="tableData.length !== 0"
      class="width-fill align-center margin-top-xs flex gap-xs"
      style="margin-bottom: -20px"
    >
      <el-tag type="danger">
        {{ formData.indicatorName }}
      </el-tag>
      <span class="fs-18 text-green">=</span>
      <template
        v-for="(item, i) in tableData"
        :key="item.indicatorId"
      >
        <span
          v-if="i === 0 && item.calculation === 2"
          class="fs-18"
        >
          0
        </span>
        <span
          v-show="
            i !== 0 || (i === 0 && item.calculation === 2)
          "
          class="fs-18"
          :class="[calculationObj[item.calculation as number].class]"
        >
          {{
            calculationObj[item.calculation as number].value
          }}
        </span>
        <el-tag>
          {{
            indicatorData.find(
              m => m.id === item.indicatorId,
            )?.indicatorName
          }}
        </el-tag>
      </template>
    </div>
    <template #footer>
      <el-button @click="handleClose">
        取消
      </el-button>
      <el-button type="primary" @click="clickSave">
        确定
      </el-button>
    </template>
  </CustomDialog>
</template>

<style lang="scss" scoped>
//------------------组件样式------------------
.dialog-container {
  height: 360px;
}
//-------------样式穿透-------------
</style>
